package com.qianfeng.android.baoman.task;

import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.qianfeng.android.baoman.Constants;
import com.qianfeng.android.baoman.util.HttpTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Android_Studio on 2015/3/16.
 * User:Maxiaoyu
 * Date:2015/3/16
 * Email:731436452@qq.com
 */
public class LoginTask extends AsyncTask<String, Integer, byte[]> {
    private TaskInterface listener;

    public LoginTask(TaskInterface listener) {
        this.listener = listener;
    }

    @Override
    protected byte[] doInBackground(String... params) {
        byte[] ret = null;
        if (params != null && params.length == 2) {
            String username = params[0];
            String userPass = params[1];
            String str1 = "http://api.ibaozou.com/api/v2/login";
            Log.i("test", "登录 url =  " + str1);
            HashMap localHashMap = new HashMap();
            localHashMap.put("username", username);
            localHashMap.put("password", userPass);
            localHashMap.put("client_id", "10230158");
            localHashMap.put("timestamp", Long.toString(System.currentTimeMillis()));
            ArrayList localArrayList = new ArrayList();
            localArrayList.add("client_id");
            localArrayList.add("username");
            localArrayList.add("password");
            localArrayList.add("timestamp");
            String str2 = Constants.getMD5Sign(localHashMap, localArrayList);
            if (TextUtils.isEmpty(str2)) {
                return ret;
            }
            localHashMap.put("sign", str2);
            ret = HttpTool.post(str1, localHashMap);
        }
        return ret;
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        super.onPostExecute(bytes);
        if (bytes != null) {
            String result = new String(bytes, 0, bytes.length);
            if (result != null) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    listener.backResult(jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
